"""
管理后台 - 数据统计接口
"""
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import func, or_
from datetime import datetime, timedelta
from typing import List

from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.core.permissions import require_permission, Permission
from app.models.user import User
from app.models.venue import Venue
from app.models.city_manager import CityManager, CityManagerStatus
from app.models.venue_feedback import VenueFeedback, FeedbackStatus
from app.schemas.common import ApiResponse
from loguru import logger

router = APIRouter(prefix="/statistics", tags=["管理后台-统计"])


@router.get("/overview", response_model=ApiResponse[dict])
@require_permission(Permission.STATS_VIEW_ALL, Permission.STATS_VIEW_CITY)
async def get_overview(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取数据概览"""
    logger.info("📊 获取数据概览")
    
    user_role = getattr(current_user, 'role', 'user')
    
    # 场地总数
    venue_query = db.query(Venue)
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city:
            venue_query = venue_query.filter(
                or_(Venue.city_name == user_city, Venue.city_id == user_city)
            )
    
    total_venues = venue_query.count()
    operating_venues = venue_query.filter(Venue.status == 'operating').count()
    
    # 今日新增场地
    today = datetime.now().date()
    today_venues = venue_query.filter(
        func.date(Venue.created_at) == today
    ).count()
    
    # 用户总数（仅超管）
    total_users = 0
    if user_role == 'super_admin':
        total_users = db.query(User).count()
    
    # 城市管理员数量（仅超管）
    total_city_managers = 0
    if user_role == 'super_admin':
        total_city_managers = db.query(CityManager).filter(
            CityManager.status == CityManagerStatus.APPROVED
        ).count()
    
    # 待处理事项
    pending_audit_venues = 0
    pending_applications = 0
    pending_feedbacks = 0
    
    if user_role == 'super_admin':
        # 待审核场地
        pending_audit_venues = db.query(Venue).filter(
            Venue.audit_status == 'pending'
        ).count()
        
        # 待审核申请
        pending_applications = db.query(CityManager).filter(
            CityManager.status == CityManagerStatus.PENDING
        ).count()
    
    # 待处理反馈
    feedback_query = db.query(VenueFeedback).filter(
        VenueFeedback.status == FeedbackStatus.PENDING
    )
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city:
            feedback_query = feedback_query.join(Venue, VenueFeedback.venue_id == Venue.id, isouter=True)
            feedback_query = feedback_query.filter(
                or_(
                    Venue.city_name == user_city,
                    Venue.city_id == user_city,
                    VenueFeedback.venue_id.is_(None)
                )
            )
    pending_feedbacks = feedback_query.count()
    
    data = {
        "totalVenues": total_venues,
        "operatingVenues": operating_venues,
        "todayVenues": today_venues,
        "totalUsers": total_users,
        "totalCityManagers": total_city_managers,
        "pendingAuditVenues": pending_audit_venues,
        "pendingApplications": pending_applications,
        "pendingFeedbacks": pending_feedbacks
    }
    
    logger.success("✅ 返回数据概览")
    
    return ApiResponse(data=data)


@router.get("/venue-trend", response_model=ApiResponse[List[dict]])
@require_permission(Permission.STATS_VIEW_ALL, Permission.STATS_VIEW_CITY)
async def get_venue_trend(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取场地增长趋势（最近30天）"""
    logger.info("📈 获取场地增长趋势")
    
    user_role = getattr(current_user, 'role', 'user')
    
    # 基础查询
    venue_query = db.query(Venue)
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city:
            venue_query = venue_query.filter(
                or_(Venue.city_name == user_city, Venue.city_id == user_city)
            )
    
    # 获取最近30天的数据
    trend_data = []
    for i in range(30, -1, -1):
        date = (datetime.now() - timedelta(days=i)).date()
        count = venue_query.filter(func.date(Venue.created_at) == date).count()
        trend_data.append({
            "date": date.isoformat(),
            "count": count
        })
    
    return ApiResponse(data=trend_data)


@router.get("/city-distribution", response_model=ApiResponse[List[dict]])
@require_permission(Permission.STATS_VIEW_ALL)
async def get_city_distribution(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取城市场地分布（仅超管）"""
    logger.info("🗺️  获取城市场地分布")
    
    # 按城市分组统计
    results = db.query(
        Venue.city_name,
        func.count(Venue.id).label('count')
    ).group_by(Venue.city_name).all()
    
    distribution = [
        {"city": r.city_name, "count": r.count}
        for r in results
    ]
    
    return ApiResponse(data=distribution)


@router.get("/venue-type-distribution", response_model=ApiResponse[List[dict]])
@require_permission(Permission.STATS_VIEW_ALL, Permission.STATS_VIEW_CITY)
async def get_venue_type_distribution(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取场地类型分布"""
    logger.info("📊 获取场地类型分布")
    
    user_role = getattr(current_user, 'role', 'user')
    
    # 基础查询
    venue_query = db.query(Venue)
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city:
            venue_query = venue_query.filter(
                or_(Venue.city_name == user_city, Venue.city_id == user_city)
            )
    
    # 简单统计（这里可以改进为更精确的统计）
    all_venues = venue_query.all()
    
    type_counts = {
        '5人': 0,
        '7人': 0,
        '11人': 0
    }
    
    for venue in all_venues:
        venue_type = venue.type or ''
        if '5' in venue_type:
            type_counts['5人'] += 1
        if '7' in venue_type:
            type_counts['7人'] += 1
        if '11' in venue_type:
            type_counts['11人'] += 1
    
    distribution = [
        {"type": k, "count": v}
        for k, v in type_counts.items()
    ]
    
    return ApiResponse(data=distribution)

